/**
 * required js:
 *    JQuery-1.7+.js
 *
 * @desc 全局变量
 * @author liuguojun
 * @date 2014-07-01        
 */
var XG_Global = {

    /**
     * 客户端标识
     */
    appId: '8888',
    
    /**
     * 客户端版本
     */
    appVersion: '4.0', 
    
    /**
     * 客户端设备标识
     */
    getDevice: function(){
        var _self = this;
        var device = XG_Store.get('_device');
        if (!device){
            device = this.uuid();
            XG_Store.set('_device', device);
        }
        
        return device;
    }, 
    
    /**
     * 获取服务端标识
     */
    getToken: function() {
        var _self = this;
        var token = XG_Store.get('_token');
        if (!token){
            token = '';
        }
        
        return token;
    }, 
    
    /**
     * 设置服务端标识
     */
    setToken: function(token) {
        if (!!token) {
            XG_Store.set('_token', token);
        }
    },

    /**
     * 动态加载js文件
     */
    loadJS: function(urls){
        if (urls.length < 1) {
            return ;
        }
        var oHead = document.getElementsByTagName('HEAD').item(0);
        var oScript= document.createElement('script');
        oScript.type = 'text/javascript';
        oScript.src = urls.shift();
        if (oScript.readyState) {
            oScript.onreadystatechange = function(){ 
                if(oScript.readyState == 'loaded' || oScript.readyState == 'complete'){ 
                    oScript.onreadystatechange = null;
                    XG_Global.loadJS(urls);
                };
            }
        } else {
            oScript.onload = function(){
                XG_Global.loadJS(urls);
            }
        }
        oHead.appendChild(oScript);
    }, 
    
    /**
     * 生产UUID
     */
    uuid: function() {
        var d = new Date().getTime();
        if(window.performance && typeof window.performance.now === "function"){
            d += performance.now();
        }
        var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random()*16)%16 | 0;
            d = Math.floor(d/16);
            return (c=='x' ? r : (r&0x3|0x8)).toString(16);
        });
        return uuid;
    },
    
    /**
     * 获取Html参数
     */
    getHtmlParams: function(){
        var url = location.href;
        var key = '';
        var param = '';
        if (arguments.length > 0) {
            key = arguments[0]
        }
        if (url.indexOf('?') > -1) {
            param = url.substring(url.indexOf('?') + 1);
        }
        if (param.length > 0 && key.length > 0) {
            var idx1 = param.indexOf(key + '=');
            if( idx1 > -1){
                param = param.substring(idx1 + key.length + 1);
                
                var idx2 = param.indexOf('&')
                if (idx2 > -1){
                    param = param.substring(0, idx2);
                }
            }
        }
        
        return param;
    },
    
    /**
     * 获取彩种名称
     *
     * @param lotteryCode 彩种代码
     */
    getLotteryName: function(lotteryCode){
        if (lotteryCode == '01') {
            return '双色球';
        } else if (lotteryCode == '05'){
            return '福彩3D';
        } else if (lotteryCode == '06'){
            return '天天彩选4';
        } else if (lotteryCode == '07'){
            return '七乐彩';
        } else if (lotteryCode == '10'){
            return '15选5';
        } else if (lotteryCode == '13'){
            return '东方6+1';
        } else {
            return '未知';
        }
    }
};

/**
 * @desc 服务类
 * @author liuguojun
 * @date 2014-08-05
 */
var XG_Service = {

    URL: '/shweb_dbs/dbs.service',


    /**
     * 打包
     * 
     * @param key
     * @return String
     */
    packet: function(service, params){
        var setting = {
            head: {
                appId: XG_Global.appId,
                appVersion: XG_Global.appVersion,
                device: XG_Global.getDevice(),
                token: XG_Global.getToken(),
                funcId: service,
                dataType: 'json'
            },
            body: {}
        };
        $.extend(setting.body, params);
        return {
            _message: JSON.stringify(setting)
        }
    },
    
    
    /**
     * 执行服务请求
     *
     * @param service 
     * @param params
     * @return Object
     */
    doService: function(service, params, callback){
        var _self = this;
        var reval = null;
        
        if (!callback) {
            $.ajax({
                type:'post', 
                url:_self.URL, 
                async:false, 
                data:_self.packet(service, params), 
                dataType:'json', 
                success:function (data) {
                    if (data.head.errcode == '0000') {
                        XG_Global.setToken(data.head.token);
                    }
                    reval = data;
                }
            });
            
            return reval;
        } else {
            $.ajax({
                type:'post', 
                url:_self.URL, 
                async:true, 
                data:params, 
                dataType:'json', 
                success:function (data) {
                    if (data.head.errcode == '0000') {
                        XG_Global.setToken(data.head.token);
                    }
                    callback(data);
                }
             });
        }
    }
};


/**
 * @desc 本地存储
 * @author liuguojun
 * @date 2014-07-09
 */
var XG_Store = {
    /*{1:cookie, 2:falsh, 3:user data, 4:localStorage}*/
    stype: 1,
    
    store: null,
    
    istype: function(){
        if (this.stype == 0) {
            var domain = location.hostname;
            this.store = window.localStorage || window.globalStorage && window.globalStorage[location.hostname];
            
            if(!!this.store){
                this.stype = 4;
            } else {
                this.store = document.createElement('input');
                if (this.store.addBehavior){
                    try {
                        this.store.type = "hidden";
                        this.store.style.display = "none";
                        this.store.addBehavior ("#default#userData");
                        document.body.appendChild(this.store);
                        var expires = new Date();
                        expires.setDate(expires.getDate() + 365);
                        this.store.expires = expires.toUTCString();
                        
                        this.stype = 3;
                    } catch(e) {
                    }
                } else {
                    if (!!navigator.cookieEnabled){
                        this.stype = 1;
                    }
                }
            }
        }
        
        return this.stype;
    },
    
    /**
     * 设置参数值
     *
     * @param key
     * @param value
     */
    set: function(key, value){
        if (this.istype() === 4) {
            this.stroe.setItem(key, value);
        } else if (this.istype() === 3) {
            this.stroe.load(location.hostname);
            this.stroe.setAttribute(key, value);
            this.stroe.save(location.hostname);
        } else if (this.istype() === 2) {
        
        } else if (this.istype() === 1) {
            var expires = new Date();
            expires.setTime(expires.getTime() +  1000 * 60 * 60 * 24 * 365);
            document.cookie = key + "=" + encodeURIComponent(value) + ";path=/" + "; expires=" + expires.toGMTString();
        }
    },
    
    /**
     * 获取参数值
     *
     * @param key
     * @return String
     */
    get: function(key){
        if (this.istype() === 4) {
            return this.stroe.getItem(key);
        } else if (this.istype() === 3) {
            this.stroe.load(location.hostname);
            return this.stroe.getAttribute(key);
        } else if (this.istype() === 2) {
        
        } else if (this.istype() === 1) {
            var key_equal = key + "=";
            if (document.cookie.length <= 0) {
                return null;
            }
            var pos_start = document.cookie.indexOf(key_equal);
            if (pos_start == -1) {
                return null;
            }
            pos_start += key_equal.length;
            pos_end = document.cookie.indexOf(";", pos_start);
            if (pos_end == -1) {
                pos_end = document.cookie.length;
            }
 
            return decodeURIComponent(document.cookie.substring(pos_start, pos_end));
        }
        
        return null;
    },
    
    /**
     * 删除参数值
     * 
     * @param key
     */
    remove: function(key){
        if (this.istype() === 4) {
            this.stroe.removeItem(key);
        } else if (this.istype() === 3) {
            this.stroe.load(location.hostname);
            this.stroe.removeAttribute(key);
            this.stroe.save(location.hostname);
        } else if (this.istype() === 2) {
        
        } else if (this.istype() === 1) {
            this.set(key, "");
        }
    }
};